<script setup>
import NavBar from "@/components/common/navbar/NavBar.vue";
import {reactive, toRefs} from "vue";
import {useRouter} from "vue-router";
import {login} from "@/network/user";
import {showSuccessToast} from "vant";
import {useStore} from "vuex";

const userInfo = reactive({
  email: '',
  password: '',
})
const {email, password,} = toRefs(userInfo)
const router = useRouter()
const store = useStore()
const onSubmit = () => {
  login(userInfo).then(res => {
    // 将返回的Token信息保存到本地 window.LocalStorage
    if (res) {
      window.localStorage.setItem('token', res['access_token'].toString());
      // 修改状态管理里的登录状态
      store.commit('setIsLogin', true)
      // 提示登录成功
      showSuccessToast('登录成功');
      // 刷新购物车
      store.dispatch('updateCart')
      // 清空表单
      email.value = '';
      password.value = '';
      // 1秒后跳转到上一页
      setTimeout(() => {
        router.push({path: '/'})
      }, 1000)
    }
  })
}
</script>

<template>
  <div>
    <nav-bar>
      <template v-slot:default>用户登录</template>
    </nav-bar>
    <div style="margin-top: 50px">
      <div style="text-align: center">
        <van-image fit="contain" height="5rem" src="https://www.lmonkey.com/_nuxt/img/logo.2a324bb.png" width="10rem">

        </van-image>
      </div>
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
              v-model="email"
              :rules="[{ required: true, message: '请填写用户名' }]"
              label="邮箱"
              name="邮箱"
              placeholder="邮箱"
          />
          <van-field
              v-model="password"
              :rules="[{ required: true, message: '请填写密码' }]"
              autocomplete="on"
              label="密码"
              name="密码"
              placeholder="密码"
              type="password"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button block color="#42b983" native-type="submit" round type="primary">
            提交
          </van-button>
          <div class="link-login" @click="router.push({path:'/register'})">没有账号？立即注册</div>
        </div>
      </van-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.link-login {
  line-height: 50px;
  font-size: 14px;
  margin-bottom: 20px;
  color: #42b983;
  display: inline-block;
}
</style>